<template>
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
        text-color="#fff"
        active-text-color="#ffd04b"
        >
        <el-menu-item index="1">单选题</el-menu-item>
        <el-menu-item index="2">多选题</el-menu-item>
        <el-menu-item index="3">判断题</el-menu-item>
        <el-menu-item index="4">分析题</el-menu-item>
    </el-menu>
  
    <!-- 题库视图 -->
    <div v-if="loadedData && loadedData.length > 0" class="container">
        <ul>
            <li v-for="(item, index) in loadedData" :key="index" class="question-item">
                <div class="question">  
                  <el-button 
                    @click="toggleSelection(item.id)"
                    :icon="Check" 
                     circle 
                    :class="{ 'selected': isSelected(item.id) }"
                  /> 
                  <h3 class="detail">{{ index + 1 }}. {{ item.topic }}</h3>
                </div>
                
                <div v-if="item.type === 1 || item.type === 2">
                    <div v-for="(option, key) in ['A', 'B', 'C', 'D']" :key="key" class="option">
                      <span :data-option-letter="option" :class="{ 'selected-answer': item.answer.includes(option) }"></span>
                      {{ item['option' + option] }}
                     <!--  <span class="detail" >{{ item['option' + option] }}</span> -->
                    </div>
                    <div v-if="item.parse" class="parse">解析: {{ item.parse }}</div>
                </div>
                <div v-else-if="item.type === 3">
                    <p class="type3or4">正确答案: {{ item.answer ? '正确' : '错误' }}</p>
                    <div v-if="item.parse" class="parse">解析: {{ item.parse }}</div>
                </div>
                <div v-else-if="item.type === 4">
                    <p class="type3or4">{{ item.answer }}</p>
                    <div v-if="item.parse" class="parse">解析: {{ item.parse }}</div>
                </div>
            </li>
        </ul>
        <div class="ensure">
          <el-button  @click="confirmSelection" type="success" plain >确认选择</el-button>
        </div>
    </div>
    <div v-else class="noData">
        <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
    </div>
    
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { interceptor } from '@/utils/interceptor'
  import { Check } from '@element-plus/icons-vue'
  
  const activeIndex = ref('1')
  const loadedData = ref([]) // 存储根据不同类型加载的数据
  const router = useRouter()
  const selectedQuestions = ref<number[]>([]) // 存储已选中的题目ID
  const allQuestionIds = ref([]) //存储所有的id
  const finalScore = ref(0) 
  
  // 加载数据的方法
  const loadDataBasedOnType = async (type) => {
  try{
    const httpInstance = interceptor()
    const response = await httpInstance.get(`/teacher/question/${type}`);
    loadedData.value = response.data.data; // 假设API响应的数据在response.data中
    //console.log("loadedDate.value[0]:",loadedData.value[0])
    if(!allQuestionIds.value.includes(loadedData.value[0])){
      for(let i=0;i<loadedData.value.length;++i){
        allQuestionIds.value.push(loadedData.value[i])
      }
    }
  } catch(error) {
    console.error(`题目加载失败:`, error);
    loadedData.value = [];
  }
  }
  
  // 处理菜单选择
  const handleSelect = (index) => {
  activeIndex.value = index;
  loadDataBasedOnType(index); // 根据选择加载数据
  }
  
  // 页面加载时自动加载首次数据
  onMounted(() => {
  loadDataBasedOnType(activeIndex.value);
  });
  
  // 切换题目选中状态
  const toggleSelection = (id: number) => {
  const index = selectedQuestions.value.indexOf(id)
  if (index > -1) {
    selectedQuestions.value.splice(index, 1); // 如果存在则移除
  } else {
    selectedQuestions.value.push(id); // 如果不存在则添加
  }
  }
  
  // 检查题目是否被选中
  const isSelected = (id: number): boolean => {
  return selectedQuestions.value.includes(id)
  }
  
  // 确认选择并组卷
  const confirmSelection = () => {
  // 获取已选择的问题ID列表
  const selectedQuestionsIds = selectedQuestions.value.map(q => q)
 // console.log("Selected Questions:", selectedQuestionsIds)
  
  //计算总分
  //console.log("allQuestionIds.value",allQuestionIds.value)
  for(let i=0;i<selectedQuestionsIds.length;++i){
    for(let j=0;j<allQuestionIds.value.length;++j){
      if(selectedQuestionsIds[i]==allQuestionIds.value[j].id){
        switch(allQuestionIds.value[j].type){
          case 1:finalScore.value+=5;break;
          case 2:finalScore.value+=5;break;
          case 3:finalScore.value+=3;break;
          case 4:finalScore.value+=20;break;
        }
                
      }
    }
  }

  // 从localStorage中读取exam表单数据并解析为对象
  const currentExamForm = JSON.parse(localStorage.getItem('currentExamForm') || '{}');
  const allData = {
    id: 0,
    name: currentExamForm.name,
    courseName: currentExamForm.courseName,
    duration: currentExamForm.duration,
    startTime: '',
    endTime: '',
    finalScore: finalScore.value,
    passingPoint: currentExamForm.passingPoint * finalScore.value * 0.01,
    remark: currentExamForm.remark,
    questionList: selectedQuestionsIds 
  }
  
  const httpInstance = interceptor()
  httpInstance.post('/teacher/exam', allData)
    .then(response => {
      if(response.data.code == 1){
        console.log("组卷成功：", response.data);
        alert("组卷成功！")
      }else{
        alert("组卷失败！")
      }
      
    })
    .catch(error => {
      console.error("组卷失败：", error);
    }) 
  }
  </script>
  
  <style scoped>

.noData img{
     max-width:100%;
     height:auto;
     
     margin-left:-20%;
  }
  
  .el-menu-demo{
  background-color:#545c64;
  }
  
  .el-menu-item{
  color:white;
  font-size:20px;
  }
  
  .container{
    width:80%;
    height: 80%;
    display: flex;
    margin-top: 40px;
    margin-left: 30px;
  }
  
  /* 选中状态下的按钮样式 */
  .selected {
    background-color: rgb(141, 237, 142);
    color: white;
  
  }
  
  .question-item {
  list-style-type: none; /* 清除项目符号 */
  margin-bottom: 20px;
  padding: 0px;
  /* border-bottom: 1px solid #eee; */
  }
  
  .question{
    display: flex;
    align-items: center; /* 垂直居中对齐 */
  }
  
  .option {
  display: inline-block;
  /* margin-left: 20px;
  margin-bottom: 10px; */
  margin: 10px 0 10px 30px;
  }
  
  .option span {
  position: relative;
  padding-left: 45px;
  }
  
  .option span::before {
  content: attr(data-option-letter);
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 35px;
  height: 35px;
  border-radius: 50%;
  border: 1px solid #ccc;
  background-color: rgba(0,0,0,0);
  display: flex;
  justify-content: center;
  align-items: center;
  color:#a4a1a1;
  font-size:18px;
  }
  
  .option .selected-answer::before {
  
  background-color: rgb(0, 153, 255);
  color:white;
  font-size:18px;
  
  }
  
  .ensure{
   display: flex;
   justify-content: flex-start;
  }
  
  .detail{
    margin-left: 10px;
    font-size:23px;
  }
  
  .type3or4{
    margin-top:12px;
    margin-left: 25px;
    font-size:18px;
  }
  
  .parse{
    font-size:10px;
    color:rgb(221, 103, 103);
  }
  </style>